<?php

//报名
class BmController extends UserBaseC {

    //京东报名
    public function actionJd() {
        $this->error('京东报名暂时关闭！');
        if (IS_POST) {
            $parse_url = parse_url($_POST['detail_url']);
            if ($parse_url['host'] == 'item.jd.com') {
                $product_id = str_replace(array('/', '.html'), '', $parse_url['path']);
                if (empty($product_id)) {
                    $this->error('获取商品ID错误！');
                }
                if (empty($_POST['nick'])) {
                    $this->error('联系旺旺不能为空！');
                }
                //标识京东
                $_POST['item_type'] = 11;
                $_POST['product_id'] = $product_id;
            } else {
                $this->error('商品地址错误，只能填写京东商城里的商品地址！');
            }
        }
        $this->actionBm('jd');
    }

    //报名
    public function actionBm($render = '') {
        SeoWord::setWord($this, 'getCatSeo', 'baoming');
        //网站配置
        $config = ConfigModel::model()->getConfig();
        $model = new GoodsBmModel();
        $key = GuestDataModel::model()->getMarkId();
        //专场报名
        $special_id = (int) $_GET['special_id'];
        $objSpecialModel = '';
        if ($special_id) {
            $objSpecialModel = SpecialModel::model()->findByPk($special_id);
            $this->assign('special_model', $objSpecialModel);
        }
        if (IS_POST) {
            //缓存刚刚填写的
            Yii::app()->cache->set($key, $_POST, 600);
            //没登录处理
            if (!Yii::app()->user->isLogged()) {
                $jump = self::U(ACTION_NAME, array('act' => 'nologin'));
                $cookie = new CHttpCookie('jump', $jump);
                Yii::app()->request->cookies['jump'] = $cookie;
                $this->error('not_logged', self::U('user/login/login'));
            } else {
                //用户类型
                if (Yii::app()->user->kind == 1) {
                    $this->error('只有商家会员才可以报名！');
                }
                if ($model->goodsMonthBmNumber(Yii::app()->user->id) !== true) {
                    $error = $model->getOneError();
                    $this->error($error ? $error : '您所在的会员类型没有报名权限！');
                }
                //判断是否绑定旺旺
                $memberTB = MembersTaobaoModel::model()->getMemberTB(Yii::app()->user->id);
                if (empty($memberTB->taobao_user_nick) && $_POST['item_type'] != 11) {
                    $this->error('请绑定旺旺后再报名！', self::U('info/aliwang'));
                }
                //手机是否绑定
                $phone = Yii::app()->user->phone;
                if (empty($phone)) {
                    $this->error('请绑定手机后再报名！', self::U('info/index'));
                }
            }
            $time = time();
            //过滤不允许直接提交的内容
            $model->filterPostData($_POST);
            if ($objSpecialModel) {
                if ($objSpecialModel->is_special) {//如果设置的时候is_special设置为0(不属于专场),则报名商品添加的时候专场ID为0
                    $_POST['special_id'] = $objSpecialModel->id;
                }
            }
            $model->attributes = $_POST;
            $model->start_time = strtotime(date('Y-m-d', $time)) + 86400 + 36000;
            $model->end_time = strtotime(date('Y-m-d', $time)) + 4 * 86400 + 36000;
            $model->uid = Yii::app()->user->id;
            if (!$model->goodsBmNumber($model->nick)) {
                $this->error($model->getOneError());
            }
            //报名后多少天可以报名检查
            if ($config['baoming_ok'] > 0) {
                $goods = $model->find($model->where(array('product_id' => $model->product_id, 'order' => 'goods_id desc')));
                if (!empty($goods)) {
                    $goods = $goods->attributes;
                }
                if (isset($goods['product_id']) && $goods['product_id'] > 0) {
                    if (isset($goods['status']) && !in_array($goods['status'], array(1, 2, 4))) {
                        $this->error('该商品还在审核中，请耐心等待审核结果！');
                    } else {
                        $min_end_time = $goods['end_time'] + ($config['baoming_ok'] * 86400);
                        if ($time < $min_end_time && $goods['status'] == 1) {
                            $pre_end_time = date('Y-m-d H:i:s', $goods['end_time']);
                            $pre_start_time = date('Y-m-d H:i:s', $goods['start_time']);
                            $this->error('对不起，宝贝“' . $model->product_id . '”在' . $pre_start_time . '至' . $pre_end_time . '上过活动，活动结束' . $config['baoming_ok'] . '天之后才能重新报名。');
                        }
                    }
                }
            }
            //同一个宝贝报名时间间隔要三天
            if ($config['baoming_no'] > 0) {
                $oldAction = GoodsActionModel::model()->find($model->where(array('product_id' => $model->product_id, 'action_type' => array('LT', 3), 'order' => 'id DESC')));
                if (!empty($oldAction) && $oldAction->action_type == 2) {
                    $min_bm_time = $oldAction->action_time + $config['baoming_no'] * 86400;
                    $bm_no_time = date('Y-m-d H:i:s', $oldAction->action_time);
                    $bm_time = date('Y-m-d H:i:s', $oldAction->baoming_time);
                    $H = $config['baoming_no'] * 24;
                    if ($time < $min_bm_time) {
                        $this->error('宝贝“' . $model->product_id . '”在' . $bm_time . '已报名，并于' . $bm_no_time . '审核不通过，审核不通过的宝贝，在' . $H . '小时之后才能重新报名。');
                    }
                }
            }
            if (mb_strlen($model->goods_name, 'utf-8') < 7) {
                $this->error('商品标题长度不能少于7个字！');
            }
            if (mb_strlen($model->goods_name, 'utf-8') > 10) {
                $this->error('商品标题长度不能超过10个字！');
            }
            if (mb_strlen($model->goods_brief, 'utf-8') < 25) {
                $this->error('商品简介长度不能小于25个字！');
            }
            //获取淘宝信息
            $data = TaobaoApi::getInstance()->getItem($model->product_id);
            if ($data['sales']) {
                $model->sales = (int) $data['sales'];
            }
            if ($data['p_price']) {
                $model->p_price = $data['p_price'];
            }
            //销量检测
            if ($model->item_type == 0) {
                if ((int) $data['sales'] < 10) {
                    $this->error('宝贝销量为' . $data['sales'] . '少于10件，建议更换其它销量10件以上的宝贝报名！');
                }
                //店铺等级检测
                $grade = TaobaoApi::getInstance()->getGrade($_POST['product_id']);
                if ($grade < 6) {
                    $this->error('店铺等级不复合要求，最低需要店铺6级才可以报名！');
                }
            }
            if ($model->validate() && $model->save()) {
                //添加日志
                GoodsActionModel::model()->goodsBmAdd($model);
                Yii::app()->cache->delete($key);
                $this->success('恭喜您，宝贝：' . $model->product_id . ' 报名成功，请耐心等待审核！', self::U('user/goodsbm/goods'));
                exit;
            } else {
                $this->error($model->getOneError());
            }
        } else {
            if (Yii::app()->user->isLogged() && Yii::app()->user->kind) {
                $this->error('只有商家会员才可以报名！');
            }
        }
        $cache = Yii::app()->cache->get($key);
        Yii::app()->cache->delete($key);
        if (empty($cache)) {
            $cache = array();
        }
        $this->assign('data', $cache);
        $this->assign('model', $model)
                ->render($render);
    }

    //获取商品信息
    public function actionIteminfo() {
        $product_id = Yii::app()->request->getParam('product_id');
        if (empty($product_id)) {
            $this->ajaxReturn(array('status' => 0));
        }
        if (!is_numeric($product_id)) {
            $parse_url = parse_url($product_id);
            if ($parse_url['host'] == 'item.jd.com') {
                $product_id = str_replace(array('/', '.html'), '', $parse_url['path']);
                if (empty($product_id)) {
                    $this->ajaxReturn(array('status' => 0));
                }
                $data = JdApi::getInstance()->getItem($product_id);
                //标识京东
                $data['item_type'] = 11;
            } else {
                //台湾淘宝
                if ($parse_url['host'] == 'tw.taobao.com') {
                    preg_match('/item\/(.*).htm/', $parse_url['path'], $match);
                    $product_id = $match[1];
                } else {
                    parse_str($parse_url['query'], $query);
                    $product_id = $query['id'];
                }
                if (empty($product_id)) {
                    $this->ajaxReturn(array('status' => 0));
                }
                $data = TaobaoApi::getInstance()->getItem($product_id);
                //缩图处理
                if (!empty($data['images'])) {
                    foreach ($data['images'] as $k => $img) {
                        preg_match("/[png|jpg|gif](_.*x.*.[png|jpg])$/", $img, $matches);
                        if (empty($matches)) {
                            $data['images'][$k] = trim($data['images'][$k]) . '_300x300.jpg';
                        } else {
                            $data['images'][$k] = str_replace($matches[1], '_300x300.jpg', $data['images'][$k]);
                        }
                    }
                    $data['pic_url'] = $data['images'][0];
                }
            }
        } else {
            $this->error('商品地址格式不正确，请填写商品链接。');
        }
        if (empty($data)) {
            $data = array('status' => 0);
        } else {
            $data['status'] = 1;
        }
        $this->ajaxReturn($data);
    }

    /**
     * 登录
     */
    public function actionLogin() {
        if (Yii::app()->user->isLogged()) {
            $this->error('您已经登录，无需重复登录！');
        }
        $username = Yii::app()->request->getParam('username');
        $password = Yii::app()->request->getParam('password');
        if (empty($username)) {
            $this->error('用户名不能为空！');
        }
        if (empty($password)) {
            $this->error('密码不能为空！');
        }
        if ($uid = Yii::app()->user->login($username, $password)) {
            if (IS_AJAX) {
                $this->ajaxReturn(array('status' => true, 'info' => '登录成功！', 'kind' => Yii::app()->user->kind));
            } else {
                $this->success('登录成功！');
            }
        } else {
            $this->error(Yii::app()->user->getError() ? Yii::app()->user->getError() : '登录失败！');
        }
    }

}
